package com.cmy.framework_base.common.loading

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import androidx.fragment.app.FragmentManager
import com.cmy.framework_base.R
import com.cmy.framework_base.basics.BasicsDialogFragment

/**
 * @name:
 *  LoadDialog
 * @package:
 *  com.cmy.framework_base.common.loading
 * @date:
 *  2023/4/2615:40
 * @author
 *    cmy
 * @description
 *  基本的显示弹窗，目前为了实现对应的弹出效果
 */
class LoadDialog : BasicsDialogFragment() {
    private var loadingRequestCount = 0;

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        dialog?.run {
            window?.setBackgroundDrawableResource(android.R.color.transparent)
            window?.requestFeature(Window.FEATURE_NO_TITLE);
            setCanceledOnTouchOutside(false);
            setCancelable(false)
        }
        return inflater.inflate(R.layout.dialog_progress_view, container, false)
    }

    override fun onStart() {
        super.onStart()
        dialog?.window?.let {
            it.attributes.dimAmount = 0.0f
        }
    }

    override fun onResume() {
        super.onResume()
        dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.parseColor("#00000000")))
    }


    fun showFragment(manager: FragmentManager, tag: String?) {
        try {
            if (!isAdded && null == manager.findFragmentByTag(tag)) {
                manager.beginTransaction().remove(this).commitAllowingStateLoss()
                manager.beginTransaction().add(this, tag).commitAllowingStateLoss()
            } else {
                manager.beginTransaction().show(this).commitAllowingStateLoss()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    override fun showNow(manager: FragmentManager, tag: String?) {
        try {
            if (this.loadingRequestCount != 0) {
                return
            }
            loadingRequestCount++
            showFragment(manager, tag)
        } catch (_: Exception) {

        }
    }

    override fun dismiss() {
        try {
            if (loadingRequestCount > 0) {
                loadingRequestCount--
            }
            if (this.loadingRequestCount != 0) {
                return
            }
            super.dismissAllowingStateLoss()
        } catch (_: Exception) {

        }
    }

}